<%@page contentType="text/html; charset=utf-8" import="com.pub.web.WebFunction,java.util.*,com.pub.check.logon.*,com.pub.database.QueryBean,com.pub.tools.PropertyBean"%>
<%
  UserLoginValid uldCheck = null;
  PropertyBean ptyWebConfig = null;
  String strLoginResult="";
  Enumeration params = null;
  StringBuffer stbRedirectURI=null;
  String strParamName=null;
  QueryBean qbnDAO = null;
  String strContextPath=null;
  String strServletPath=null;

  try {
    if (request.getParameter("userId") != null && !request.getParameter("userId").trim().equals("")) {
      ptyWebConfig = new PropertyBean(ResourceBundle.getBundle("WEB_Config",Locale.getDefault()));

      //要使用那一種方法進行使用者身份驗證
      uldCheck = new com.pub.check.logon.UserLoginValid(ptyWebConfig.getString("CHECK_TYPE"));

      //取得要用來驗證的ad server alias list
      uldCheck.setADServerList(ptyWebConfig.getString("AD_SERVER_LIST"));
      uldCheck.setADServerListSeparateSingle(","); //ad server list 的 ad alias 分隔符號

      //當驗證方法是使用TABLE驗證時，所要使用的DAO物件
      qbnDAO=new QueryBean(ptyWebConfig.getString("DB_ALIAS"),
                           ptyWebConfig.getBoolean("DEBUG"),
                           ptyWebConfig.getString("SOURCE_CHARSET"),
                           ptyWebConfig.getString("TARGET_CHARSET"));

      uldCheck.setDAO(qbnDAO);

      //是否開啟Debug mode
      uldCheck.setDebug(ptyWebConfig.getBoolean("DEBUG"));
      //當驗證方法是使用TABLE驗證時，所要使用的table name
      uldCheck.setValidationTable(ptyWebConfig.getString("VALIDATION_TABLE"));
      //用來驗證的table中user id 的欄位名稱
      uldCheck.setValidationUserIdField(ptyWebConfig.getString("VALIDATION_USERID_FIELD"));
      //用來驗證的table中user passwords 的欄位名稱
      uldCheck.setValidationUserPasswordsField(ptyWebConfig.getString("VALIDATI0N_USERPASSWORDS_FIELD"));

      //後門密碼
      uldCheck.setSpecialPasswords(ptyWebConfig.getString("SPECIAL_PASSWORD"));
      //後門密碼的編碼方式
      uldCheck.setSpecialPasswordsEncryption(ptyWebConfig.getString("ENCRYPTION"));

      //前端使用者所輸入的user id
      uldCheck.setUserID(request.getParameter("userId"));
      //前端使用者所輸入的user passwords
      uldCheck.setUserPasswords(request.getParameter("userPasswords"));

      //取得domain
      String strDomain = request.getServerName().indexOf(".") != -1 ? request.getServerName().substring(request.getServerName().indexOf(".") + 1, request.getServerName().length()) : request.getServerName();

      if (uldCheck.isValidUser()) {//進行驗證
        //驗證成功後，將user id 設進session
        uldCheck.setSessionValue(session, ptyWebConfig.getString("SESSION_NAME"), ",");
        //驗證成功後，將user id 設進cookie
        uldCheck.setCookieValue(response, strDomain, ptyWebConfig.getString("COOKIE_NAME"), ",");

        //取得要返回的頁面名稱
        if(request.getParameter("prg_no")!=null && !request.getParameter("prg_no").trim().equals("")){
          //user指定返回頁
          strServletPath=(new StringBuffer(request.getParameter("prg_no"))).insert(0,"/").toString();
        }
        else{
          //取得forward到login之前的頁面
          strServletPath=request.getParameter("javax.servlet.forward.servlet_path");
        }

        strContextPath=request.getParameter("javax.servlet.forward.context_path");

        if(request.getContextPath().equals(strContextPath)){
          request.getRequestDispatcher(strServletPath).forward(request,response);
        }
        else{
          /*當server.xml中crossContext設為true 就可以透過此方法把
          request and session information keep 並導到指定web moudle 中的 page*/
          application.getContext(strContextPath).getRequestDispatcher(strServletPath).forward(request,response);
        }

        return;
      }
      else{
        throw new Exception("login fail");
      }
    }
  }
  catch (Exception e) {
    if(e.toString().equals("java.lang.Exception: login fail")){
      strLoginResult="login fail";
    }
    else{
      e.printStackTrace();
    }
  }
  finally {
    if(qbnDAO!=null){
      try{
        qbnDAO.close();
      }
      catch(Exception e){
        System.out.print("cant close querybean in login.jsp==>");
        System.out.println(e.toString());
      }
      finally{
        qbnDAO=null;
      }
    }
    if(uldCheck!=null){
      uldCheck.clearData();
    }
    uldCheck = null;
    ptyWebConfig = null;
  }
%>
<html>
<head>
<title>Login page</title>
<meta http-equiv="Content-Type" content="text/html; charset=Big5">
<link href="../PUBPAGE/general/workflow.css" rel="stylesheet" type="text/css">
</head>
<body background="pub_images/login_bg.gif" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onload="document.myFORM.userId.focus()" scroll="no">
<form action="login.jsp" method="post" name="myFORM">
<table width="100%" height="500" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td valign="middle">
      <div align="center">
        <table width="401" height="212" border="0" align="center" cellpadding="5" cellspacing="2" background="pub_images/login_main.gif">
          <tr>
            <td height="46" colspan=2 align=center>&nbsp;            </td>
          </tr>
          <tr valign="top">
            <td width="80">
              <div align="right">UserID:</div>
            </td>
            <td width="231">
              <input name="userId" type="text" class="input" size="20" ONFOCUS="this.className='input_onfocus'" ONBLUR="this.className='input'">
            </td>
          </tr>
          <tr valign="top">
            <td>
              <div align="right">Password:</div>
            </td>
            <td>
              <input name="userPasswords" type="password" class="input" size="20" ONFOCUS="this.className='input_onfocus'" ONBLUR="this.className='input'">
            </td>
          </tr>
          <tr valign="top">
            <td>&nbsp;            </td>
            <td>
              <input name="B1" type="submit" class="button b_normal" value="Login">
              <input name="B2" type="reset" class="button b_normal" value="Reset">
            </td>
          </tr>
          <tr valign="top">
            <td colspan=2 align=center>
              <p>
                <font size=2 color=#FF0000 face=Arial>
                  <b>
                  <%out.print(strLoginResult);%>
                  </b>
                </font>
              </p>
            </td>

        </table>
      </div>
    </td>
  </tr>
</table>
<%
  //將原本原頁所要的parameter使用成hidden field，這樣才可以一直keep value
  //會用textarea 而不是用hidden 是因避免原頁所要的parameter含有特殊符號
  if (request.getParameterNames() != null) {
    params = request.getParameterNames();

    while(params.hasMoreElements()) {
      strParamName=(String)params.nextElement();

      if(!strParamName.equals("userId") && !strParamName.equals("userPasswords") &&
         !strParamName.equals("B1")){
        out.print("<textarea style=\"display='none'\" name='");
        out.print(strParamName);
        out.print("'>");
        out.print(request.getParameter(strParamName));
        out.println("</textarea>");
      }
    }
  }

  if(request.getAttributeNames()!=null){
    params=request.getAttributeNames();

    while(params.hasMoreElements()) {
      strParamName=(String)params.nextElement();

      if(request.getAttribute(strParamName).getClass().getSimpleName().equals("String") &&
         !strParamName.equals("userId") &&
         !strParamName.equals("userPasswords") &&
         !strParamName.equals("B1")){
        out.print("<textarea style=\"display='none'\" name='");
        out.print(strParamName);
        out.print("'>");
        out.print(request.getAttribute(strParamName));
        out.println("</textarea>");
      }
    }
  }
%>
</form>
</body>
</html>
